package com.kh.shj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kh.shj.entity.Classify;
import com.kh.shj.mapper.ClassifyMapper;
import com.kh.shj.service.IClassifyService;
import com.kh.shj.vo.ClassifyTreeVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClassifyServiceImpl
        extends ServiceImpl<ClassifyMapper, Classify>
implements IClassifyService {


    @Resource
    private ClassifyMapper classifyMapper;

    /**
     * 构建树形商品分类列表(递归算法)
     * @return
     */
    @Override
    public List<ClassifyTreeVO> listClassifyWithTree() {
        // 获取所有商品分类树节点
        //QueryWrapper<Classify> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("parent_id",-1);
        List<Classify> allNodes = classifyMapper.selectList(null);
        // 循环遍历第一级树节点 (Stream API流)
        List<ClassifyTreeVO> classifyTreeVOList = allNodes.stream().filter(node -> node.getParentId() == -1).map(classify -> {
            ClassifyTreeVO classifyTreeVO = new ClassifyTreeVO();
            classifyTreeVO.setId(classify.getId());
            classifyTreeVO.setName(classify.getName());
            classifyTreeVO.setIcon(classify.getIcon());
            classifyTreeVO.setOrderNum(classify.getOrderNum());
            classifyTreeVO.setChildren(getChildren(classifyTreeVO,allNodes));
            return classifyTreeVO;
        }).sorted(Comparator.comparing(ClassifyTreeVO::getOrderNum)).collect(Collectors.toList());
        return classifyTreeVOList;
    }


    /**
     * 递归当前节点下是否有子节点
     * @param currentNode
     * @return
     */
    private List<ClassifyTreeVO> getChildren(ClassifyTreeVO currentNode,
                                             List<Classify> allNodes) {
        List<ClassifyTreeVO> childNodes = allNodes.stream().filter(childNode -> childNode.getParentId() == currentNode.getId()).map(classify -> {
            ClassifyTreeVO classifyTreeVO = new ClassifyTreeVO();
            classifyTreeVO.setId(classify.getId());
            classifyTreeVO.setName(classify.getName());
            classifyTreeVO.setIcon(classify.getIcon());
            classifyTreeVO.setOrderNum(classify.getOrderNum());
            classifyTreeVO.setChildren(getChildren(classifyTreeVO, allNodes)); // 递归
            return classifyTreeVO;
        }).sorted(Comparator.comparing(ClassifyTreeVO::getOrderNum)).collect(Collectors.toList());
        return childNodes;
    }
}
